<template>
  <div class="approve-list">
    <div class="approve-list_header">
      <div class="custom-tabs">
        <div
          :class="{ 'custom-tabs_item-active': filterTab === item.value }"
          v-for="item in auditType"
          :key="item.value"
          @click="changeAuditType(item.value)"
        >
          {{ item.label }}
        </div>
      </div>
      <div class="check-more" @click="handelCheckMore">
        <span class="check-more__label">查看更多</span>
        <icon-double-right :style="{ color: '#007DFF' }" />
      </div>
    </div>
    <div class="approve-list_state">
      <a-spin :loading="isAuditLoading">
        <template v-if="homeAuditList.length">
          <div class="approve-list_state-item" v-for="item in homeAuditList" :key="item.dataId" @click="showApproveDrawer(item)">
            <div class="item-content">
              <div class="title">{{ item.title }}</div>
              <div class="info">
                发起人：{{ item.user }} |
                {{ item.createTime }}
              </div>
            </div>
            <GiSvgIcon name="file-icon" size="24" />
          </div>
        </template>
        <a-empty v-else description="这里暂时什么都没有哦~">
          <template #image>
            <img :src="homeAuditIcon" alt="" />
          </template>
        </a-empty>
      </a-spin>
    </div>

    <!--  todo: 和审批页列表相同  -->
    <!--  审批 start  -->
    <div class="approve-drawer">
      <a-drawer
        :visible="isShowAuditDrawer"
        :footer="false"
        :width="900"
        title-align="start"
        :header="false"
        :render-to-body="false"
        unmountOnClose
      >
        <div class="drawer-container">
          <div class="drawer-title">
            <custom-title :title="drawerTitle" />
            <IconClose style="cursor: pointer" @click="handleDrawerCancel(false)" />
          </div>
          <div class="drawer-body">
            <!--         审批表单 start   -->
            <div
              class="drawer-body__form"
              :style="{
                height: isAcceptanceTask ? 'calc(100vh - 113px)' : 'calc(100vh - 60px)',
                'padding-top': isAcceptanceTask ? '0px' : '20px'
              }"
            >
              <a-button type="text" class="check-button" @click="handelCheckStandard" v-show="isAcceptanceTask"
                >查看标准</a-button
              >
              <div class="drawer-body__form__items" v-if="isShowAuditDrawer">
                <div>审批ID：{{ auditInstanceId }}</div>
                <micro-app
                  class="micro-app"
                  name="form-design-home-audit"
                  :url="appUrlconfig.formDesign"
                  baseroute="/form-design"
                  default-page="/home"
                  fiber
                  :data="{ token: getToken() }"
                  router-mode="native"
                />
              </div>
            </div>
            <!--         审批表单 end   -->
            <div class="drawer-body__audit">
              <div>审批记录</div>
              <div class="audit-list">
                <template v-if="auditRecordList.length">
                  <div class="audit-item" v-for="item in auditRecordList" :key="item.nodeId">
                    <div class="audit-header">
                      <img :src="Avatar" alt="" />
                      <div>
                        <div class="audit-title">
                          {{ item.name }} <span>{{ item.finishTime }}</span>
                        </div>
                        <div class="audit-status">{{ auditUser(item) }}({{ auditResult(item) }})</div>
                      </div>
                    </div>
                    <div :class="{ 'audit-desc': true, divider: true }">
                      <div class="content" v-show="item.comment?.length">
                        <a-textarea :default-value="comment(item)" auto-size disabled />
                      </div>
                    </div>
                  </div>
                </template>
              </div>
              <div class="audit-button" v-if="isOption">
                <a-textarea v-model="commentData" placeholder="请输入审批意见" />
                <div class="form-buttons">
                  <a-button class="form-buttons--refuse" @click="handelAuditRefuse">拒绝</a-button>
                  <a-button type="primary" @click="handelAuditAgree">同意</a-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-drawer>
    </div>
    <!--   审批 end -->

    <!--    验收标准 start-->
    <a-modal v-model:visible="isShowStandard" unmount-on-close :width="900" title-align="start">
      <template #title>
        <CustomTitle title="查看" />
      </template>
      <template #footer><div></div></template>
      <a-form :model="standardForm" auto-label-width>
        <template v-for="(item, index) in standardForm.fieldData" :key="`${item.fieldName}${index}`">
          <a-form-item :label="item.fieldName" v-if="!item.valueComplex">
            <a-textarea :auto-size="{ minRows: 3 }" v-model="item.fieldValue" readonly />
          </a-form-item>
          <a-form-item v-if="item.valueComplex && item.fieldValue.length" :label="item.fieldName">
            <a-image-preview-group infinite v-if="item.fileContextType === 'image'">
              <a-space wrap>
                <a-image
                  v-for="imgItem in item.fieldValue"
                  :key="imgItem.fileId"
                  :src="imgItem.fileUrl"
                  width="80"
                  height="80"
                  fit="cover"
                />
              </a-space>
            </a-image-preview-group>
            <a-space wrap v-if="item.fileContextType === 'video'">
              <video
                v-for="videoItem in item.fieldValue"
                :key="videoItem.fileId"
                @click="handlePreview(videoItem.fileUrl)"
                :src="videoItem.fileUrl"
                style="width: 80px; height: 80px; object-fit: cover"
              ></video>
            </a-space>
          </a-form-item>
        </template>
      </a-form>
    </a-modal>
    <!--    验收标准 end-->

    <!--   预览视频 start -->
    <a-modal v-model:visible="isShowPreview" unmount-on-close title-align="start" :width="900">
      <template #title>
        <CustomTitle title="视频预览" />
      </template>
      <template #footer><div></div></template>
      <video
        v-if="isShowPreview"
        :src="previewVideoUrl"
        controls
        style="width: 100%; height: 50vh; object-fit: cover; cursor: pointer"
      ></video>
    </a-modal>
    <!--  预览视频 end  -->
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { Message } from "@arco-design/web-vue";
import { useRouter } from "vue-router";
import appUrlconfig from "@/config/appUrlconfig";
import { auditType } from "@/views/home/config";
import { getToken } from "@/utils/auth";
import { mainSendForceSetData, unmountApp } from "@/microApp/utils";
import { workbenchMsgList, standardInfoByBusinessKey } from "@/apis";
import { auditStatusMap } from "./config";
import { handlerTask, approvalDataByInstanceId } from "@/apis/audit";
import type { WorkbenchMsgListParams, StandardForm, AuditRecordItem } from "@/apis";
import Avatar from "@/assets/images/default-avatar.png";
import homeAuditIcon from "@/assets/images/home-audit-icon.png";

defineProps({
  filterTab: String,
  auditMsgStatus: String
});
const emit = defineEmits(["changeFilterTab", "drawerMsgCancel"]);
const router = useRouter();

const auditTypeStr = ref("processAccept");

const changeAuditType = (type: string) => {
  emit("changeFilterTab", type);
};
/**
 * 审批列表
 */
const isAuditLoading = ref(false);
const homeAuditList = ref<any[]>([]);
const getWorkbenchMsgList = async (params: WorkbenchMsgListParams) => {
  try {
    isAuditLoading.value = true;
    const { data } = await workbenchMsgList(params);
    homeAuditList.value = data?.list ?? [];
    isAuditLoading.value = false;
  } catch (err) {
    isAuditLoading.value = false;
  }
};
/**
 * 查看更多
 */
const handelCheckMore = () => {
  router.push("/audit");
};

/**
 * 审批
 */
const isShowAuditDrawer = ref(false);
const drawerTitle = ref("");
const auditInstanceId = ref("");
const isOption = ref(false);
const auditPostData = ref<any>({});
const auditRecordList = ref<AuditRecordItem[]>([]);
const auditResult = computed(() => {
  return (data: any) => {
    if (!data?.result) {
      return "审批中";
    }
    return auditStatusMap.get(data.result) || "";
  };
});
const auditUser = computed(() => {
  return (data: any) => {
    return data.user?.name || "";
  };
});
const comment = computed(() => {
  return (data: any) => {
    return data?.comment?.length ? data?.comment[0]?.text : "";
  };
});
// 打开审批弹窗
const showApproveDrawer = (data: any) => {
  isShowAuditDrawer.value = true;
  drawerTitle.value = data.title;
  auditPostData.value.taskId = data.taskId;
  auditPostData.value.instanceId = data.dataId;
  auditPostData.value.processDefId = data.processDefId;
  auditPostData.value.nodeId = data.nodeId;
  getApprovalDataByInstanceId(data.processDefId, data.dataId);
  mainSendForceSetData("form-design-home-audit", {
    auditData: { ...data, instanceId: data.dataId },
    isHomeAudit: true // 表单禁用
  });
};
const handleDrawerCancel = (isRefresh: boolean) => {
  isShowAuditDrawer.value = false;
  commentData.value = "";
  auditRecordList.value = [];
  auditPostData.value = {};
  unmountApp("form-design-audit");
  emit("drawerMsgCancel", isRefresh);
};
/**
 * 审批数据&审批记录
 * @param defId
 * @param dataId
 */
const getApprovalDataByInstanceId = async (defId: string, dataId: string) => {
  const { data } = await approvalDataByInstanceId(defId, dataId);
  // 需要我审批的 & 待审批 RUNNING  REFUSE  PASS
  auditInstanceId.value = data?.instanceId ?? "";
  isOption.value = auditTypeStr.value === "processAccept" && data.result === "RUNNING";
  isAcceptanceTask.value = data?.formId && data.formId.includes("acceptance");
  businessKey.value = data?.processProgressVo?.businessKey ?? "";
  auditRecordList.value = data?.processProgressVo?.progress ?? [];
  auditPostData.value.formData = data?.formData ?? {};
};

/**
 * 提交审批
 */
const commentData = ref("");
const handelAuditAgree = async () => {
  auditPostData.value.action = "agree";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  handleDrawerCancel(true);
  Message.success("操作成功");
};
const handelAuditRefuse = async () => {
  auditPostData.value.action = "refuse";
  commentData.value && (auditPostData.value.comment = { text: commentData.value });
  await handlerTask(auditPostData.value);
  handleDrawerCancel(true);
  Message.success("操作成功");
};

/**
 * 验收审批-查看验收标准
 */
const isShowStandard = ref(false);
const isAcceptanceTask = ref(false);
const businessKey = ref("");
const standardForm = ref<StandardForm>({
  imageList: [],
  videoList: [],
  fieldData: []
});
const previewVideoUrl = ref("");
const handelCheckStandard = async () => {
  const { data } = await standardInfoByBusinessKey(businessKey.value);
  if (!data) return Message.error("数据错误");
  standardForm.value.fieldData = data || [];
  isShowStandard.value = true;
};
/**
 * 预览视频
 * @param url
 */
const isShowPreview = ref(false);
const handlePreview = (url: string) => {
  previewVideoUrl.value = url;
  isShowPreview.value = true;
};

defineExpose({
  getWorkbenchMsgList
});
</script>

<style scoped lang="scss">
.approve-list {
  @include flex-column;
  width: 100%;
  padding: 18px 0 0 20px;

  &_header {
    @include flex-between;
    margin-bottom: 12px;
    padding-right: 20px;
  }

  &_state {
    flex: 1;
    position: relative;
    padding-right: 20px;
    &-item {
      @include flex-between;
      align-items: center;
      padding: 4px 10px;
      box-sizing: border-box;
      background-color: #f5f7fa;
      border-radius: 4px;
      cursor: pointer;

      & + .approve-list_state-item {
        margin-top: 4px;
      }

      .item-content {
        .title {
          margin-bottom: 3px;
          font-size: 14px;
          color: #3d3d3d;
          line-height: 20px;
        }

        .info {
          font-size: 12px;
          color: #989ea8;
          line-height: 17px;
        }
      }
    }
    :deep(.arco-empty) {
      @include position-center;
    }
  }

  :deep(.arco-spin) {
    width: 100%;
    height: 100%;
  }
}

.check-more {
  @include flex-align;
  cursor: pointer;
  &__label {
    font-weight: 400;
    font-size: 14px;
    color: #409eff;
    line-height: 24px;
  }
}

.approve-drawer {
  :deep(.arco-drawer-body) {
    padding: 0;
  }
  .drawer-container {
    .drawer-title {
      @include flex-between;
      align-items: center;
      padding: 25px 20px 10px;
      border-bottom: 1px solid #dcdfe6;
      :deep(.arco-icon) {
        font-size: 24px;
        color: #86909c;
      }
    }
    .drawer-body {
      @include flex;
      &__form {
        height: 100%;
        width: 50%;
        padding: 20px 16px;
        box-sizing: border-box;
        border-right: 1px solid #dcdfe6;
        .check-button {
          margin: 10px 0;
          padding-left: 0;
        }
        &__items {
          height: calc(100vh - 113px);
          overflow-y: auto;
          padding: 10px;
          box-sizing: border-box;
          background-color: #f6f8fa;
          border: 1px solid #dcdfe6;
          .micro-app,
          :deep(micro-app-body) {
            min-width: 100% !important;
          }
        }
      }
      &__audit {
        width: 50%;
        height: 100%;
        padding: 20px 16px;
        box-sizing: border-box;
        .audit-list {
          height: calc(100vh - 304px);
          overflow-y: scroll;
          margin: 30px 0;
          padding-right: 10px;
          .audit-item {
            .audit-header {
              @include flex-center;

              img {
                width: 40px;
                height: 40px;
                border-radius: 50%;
              }

              > div {
                margin-left: 16px;
                width: 100%;

                .audit-title {
                  @include flex-between;
                }
              }
            }

            .audit-desc,
            .audit-status,
            .content,
            span {
              color: #86909c;
              font-size: 12px;
            }
            .audit-desc,
            .divider {
              margin-left: 20px;
              border-left: 1px solid rgb(var(--gray-2));
            }
            .divider {
              height: 90px;
            }
            .audit-desc {
              box-sizing: border-box;
              .content {
                width: 100%;
                padding: 12px;
                box-sizing: border-box;
                border-radius: 4px;
              }
            }
          }
        }
        .audit-button {
          width: calc(100% - 40px);
          .form-buttons {
            @include flex;
            justify-content: center;
            gap: 20px;
            margin-top: 30px;
            &--refuse {
              background-color: #f2f3f5;
            }
            :deep(.arco-btn) {
              width: 92px;
              border: 0;
            }
          }
        }
      }
    }
  }
}
</style>
